package com.hangwei.paperless.fragment.sub;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.hangwei.paperless.R;
import com.hangwei.paperless.SubRepairActivity;
import com.hangwei.paperless.adapter.PNAdapter;
import com.hangwei.paperless.model.bean.BasicInfoBean;
import com.hangwei.paperless.model.bean.PNBean;
import com.hangwei.paperless.presenter.PNPresenter;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.widget.MyTextWatcher;
import com.twelve.all.base.LoadFragment;
import com.twelve.all.net.API;
import com.twelve.all.net.CallBack;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.NotFastClickListener;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;
import com.twelve.all.utils.Tools;

import java.util.List;

/**
 * Created by 张龙臣 on 2020/11/27.
 */

public class SubBaseInfoFragment extends LoadFragment {

    private String mBillId;
    private Boolean mIsLotDataSheet;
    private EditText mTvSn;
    private EditText mEtPN;
    private EditText mTvActualHour;
    private EditText mTvRouterPN;
    private PNAdapter mPnAdapter;
    private PNPresenter mPnPresenter;
    private PopupWindow mPopupWindow;
    private String partnoId;
    private SubRepairActivity mActivity;

    @Override
    protected View onRealCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mBillId = arguments.getString("billId");
            mActivity = (SubRepairActivity) getActivity();
        }
        final View inflate = inflater.inflate(R.layout.fragment_sub_base_info, container, false);
        final TextView tvSave = inflate.findViewById(R.id.tvSave);
        mEtPN = inflate.findViewById(R.id.etPN);
        final TextView tvMaterial = inflate.findViewById(R.id.tvMaterial);
        final TextView tvDate = inflate.findViewById(R.id.tvDate);
        final TextView tvWorkTime = inflate.findViewById(R.id.tvWorkTime);
        final TextView tvLLP = inflate.findViewById(R.id.tvLLP);
        final SimpleDraweeView sdvPreparedBySign = inflate.findViewById(R.id.sdvPreparedBySign);
        final TextView tvPreparedByDate = inflate.findViewById(R.id.tvPreparedByDate);
        final SimpleDraweeView sdvCheckedBySign = inflate.findViewById(R.id.sdvCheckedBySign);
        final TextView tvCheckedByData = inflate.findViewById(R.id.tvCheckedByData);
        final TextView tvProduct = inflate.findViewById(R.id.tvProduct);
        final TextView tvNum = inflate.findViewById(R.id.tvNum);
        final TextView tvDes = inflate.findViewById(R.id.tvDes);
        final ImageView ivApproved = inflate.findViewById(R.id.ivApproved);
        final ImageView ivPrepared = inflate.findViewById(R.id.ivPrepared);
        final ImageView ivChecked = inflate.findViewById(R.id.ivChecked);
        final RelativeLayout rlRouterPN = inflate.findViewById(R.id.rlRouterPN);
        mTvRouterPN = inflate.findViewById(R.id.tvRouterPN);
        final RelativeLayout rlSN = inflate.findViewById(R.id.rlSN);
        mTvSn = inflate.findViewById(R.id.tvSn);
        final TextView tvManual = inflate.findViewById(R.id.tvManual);
        mTvActualHour = inflate.findViewById(R.id.tvActualHour);
        final TextView tvLOTSheet = inflate.findViewById(R.id.tvLOTSheet);
        final TextView tvApprovedByDate = inflate.findViewById(R.id.tvApprovedByDate);
        final SimpleDraweeView sdvApprovedBySign = inflate.findViewById(R.id.sdvApprovedBySign);
        tvSave.setOnClickListener(mListener);
        final LoadingDialog dialog = new LoadingDialog(getContext());
        dialog.show();
        String userId = SPUtil.getString(SPKey.Account.USER_ID);
        StaticPresenter.getRoutingSheetInfo(userId, mBillId, new CallBack<BasicInfoBean>() {
            @Override
            public void onCompleted(BasicInfoBean bean) {
                dialog.dismiss();
                if (bean!=null){
                    SubRepairActivity.mApn = bean.pnNHA;
                    SubRepairActivity.pwoNo = bean.pwoNo;
//                    mActivity.setStep(basicInfoBean.curExStep);
                }
                if (!bean.isLotDataSheet) {
                    partnoId = bean.partnoId;
                    mEtPN.setText(Tools.checkedString(bean.pnNHA));
                    mTvRouterPN.setText(Tools.checkedString(bean.partno));
                    mTvSn.setText(Tools.checkedString(bean.sn));
                    if (bean.manualList != null && bean.manualList.size() > 0) {
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < bean.manualList.size(); i++) {
                            BasicInfoBean.ManualListBean listBean = bean.manualList.get(i);
                            if (listBean.disabled)
                                builder.append("<font color='#ff0000' >").append(listBean.revNo).append("</font>");
                            else
                                builder.append("<font color='#333333' >").append(listBean.revNo).append("</font>");
                            if (i != bean.manualList.size() - 1)
                                builder.append("<font color='#ff0000' >,&nbsp</font>");
                        }
                        tvManual.setText(Html.fromHtml(builder.toString()));
                    } else
                        tvManual.setText("");
                    rlRouterPN.setOnClickListener(mListener);
                    rlSN.setOnClickListener(mListener);
                    mEtPN.setEnabled(true);
                    mTvRouterPN.setEnabled(true);
                    mTvSn.setEnabled(true);
                } else {
                    mEtPN.setText("N/A");
                    mTvRouterPN.setText("N/A");
                    mTvSn.setText("N/A");
                    tvManual.setText("N/A");
                    mEtPN.setEnabled(false);
                    mTvRouterPN.setEnabled(false);
                    mTvSn.setEnabled(false);
                }

                tvProduct.setText(Tools.checkedString(bean.product));
                tvNum.setText(Tools.checkedString(bean.number));
                tvDes.setText(Tools.checkedString(bean.description));
                tvMaterial.setText(Tools.checkedString(bean.material));
                tvDate.setText(Tools.checkedString(bean.revVersion));
                tvWorkTime.setText(Tools.checkedString(bean.standardMH));
                tvLLP.setText(Tools.checkedString(bean.isLLP));
                mTvActualHour.setText(Tools.checkedString(bean.actualMH));
                tvLOTSheet.setText(Tools.checkedString(bean.isLotDataSheet));
//                tvManual.setText(Tools.checkedString(bean.isLotDataSheet));

                if (bean.preparedById == null) {
                    sdvPreparedBySign.setVisibility(View.GONE);
                    tvPreparedByDate.setVisibility(View.GONE);
                    ivPrepared.setVisibility(View.VISIBLE);
                    ivPrepared.setOnClickListener(mListener);
                } else {
                    sdvPreparedBySign.setVisibility(View.VISIBLE);
                    tvPreparedByDate.setVisibility(View.VISIBLE);
                    ivPrepared.setVisibility(View.GONE);
                    sdvPreparedBySign.setImageURI(API.BASE_URL + bean.preparedBySign);
                    tvPreparedByDate.setText(bean.preparedDate);
                }
                if (bean.checkedById == null) {
                    sdvCheckedBySign.setVisibility(View.GONE);
                    tvCheckedByData.setVisibility(View.GONE);
                    ivChecked.setVisibility(View.VISIBLE);
                    ivChecked.setOnClickListener(mListener);
                } else {
                    sdvCheckedBySign.setVisibility(View.VISIBLE);
                    tvCheckedByData.setVisibility(View.VISIBLE);
                    ivChecked.setVisibility(View.GONE);
                    sdvCheckedBySign.setImageURI(API.BASE_URL + bean.checkedBySign);
                    tvCheckedByData.setText(bean.checkedDate);
                }
                if (bean.approvedById == null) {
                    sdvApprovedBySign.setVisibility(View.GONE);
                    tvApprovedByDate.setVisibility(View.GONE);
                    ivApproved.setVisibility(View.VISIBLE);
                    ivApproved.setOnClickListener(mListener);
                } else {
                    sdvApprovedBySign.setVisibility(View.VISIBLE);
                    tvApprovedByDate.setVisibility(View.VISIBLE);
                    ivApproved.setVisibility(View.GONE);
                    sdvApprovedBySign.setImageURI(API.BASE_URL + bean.approvedBySign);
                    tvApprovedByDate.setText(bean.approvedDate);
                }
                mIsLotDataSheet = bean.isLotDataSheet;
                if (mPopupWindow != null && mPopupWindow.isShowing()) mPopupWindow.dismiss();
//                if (mIsLotDataSheet) {//是否成批零件记录单
//                    tvSave.setText("保存 Save");
//                } else {
//                    tvSave.setText("下一步");
//                }
                assert getActivity() != null;
                Tools.closeSoftInputFromWindow(getActivity());
            }

            @Override
            public void onError() {
                dialog.dismiss();
                onLoadError();
            }
        });

        mTvRouterPN.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!mPopupWindow.isShowing())
                    mPopupWindow.showAsDropDown(mTvRouterPN);
                String pn = mTvRouterPN.getText().toString().trim();
                mPnPresenter.setPn(pn);
                mPnPresenter.refresh(new CallBack<List<PNBean>>() {
                    @Override
                    public void onCompleted(List<PNBean> pnBeans) {
                        if (pnBeans == null || pnBeans.size() == 0) {
                            if (mPopupWindow.isShowing()) {
                                mPopupWindow.dismiss();
                            }
                        }
                    }

                    @Override
                    public void onError() {

                    }
                });
            }
        });
        mTvRouterPN.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (!mPopupWindow.isShowing())
                        mPopupWindow.showAsDropDown(mTvRouterPN);
                    String pn = mTvRouterPN.getText().toString().trim();
                    mPnPresenter.setPn(pn);
                    mPnPresenter.refresh();
                } else {
                    if (mPopupWindow.isShowing()) {
                        mPopupWindow.dismiss();
                    }
                }
            }
        });
        Tools.closeSoftInputFromWindow(container.getContext(), mTvRouterPN);
        mPopupWindow = new PopupWindow(getActivity());
        View view = inflater.inflate(R.layout.pop_home_choose, null);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mPnAdapter = new PNAdapter(null) {
            @Override
            protected void onAdapterItemClick(PNBean item) {
                partnoId = item.id;
                mTvRouterPN.setText(Tools.checkedString(item.number));
                if (mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                }
            }
        };
        recyclerView.setAdapter(mPnAdapter);
        mPnPresenter = new PNPresenter(null, mPnAdapter);
        mPopupWindow.setContentView(view);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
//        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        return inflate;
    }
//    saveRoutingSheet  成批零件是下一步  无保存

    private NotFastClickListener mListener = new NotFastClickListener() {
        @Override
        protected void isNotFastClick(View v) {
            switch (v.getId()) {
//                case R.id.ivApproved:
//                    break;
//                case R.id.ivPrepared:
//                    break;
//                case R.id.ivChecked:
//                    break;
//                case R.id.rlRouterPN:
//                    break;
//                case R.id.rlSN:
//                    break;
                case R.id.tvSave:
                    assert getActivity() != null;
                    final LoadingDialog loadingDialog = new LoadingDialog(getActivity());
                    loadingDialog.show();
                    String userId = SPUtil.getString(SPKey.Account.USER_ID);
                    String pn = mEtPN.getText().toString().trim();
                    String sn = mTvSn.getText().toString().trim();
                    String actualHour = mTvActualHour.getText().toString().trim();
                    StaticPresenter.saveRoutingSheet(userId, mBillId, pn, partnoId, sn, actualHour, new CallBack<Object>() {
                        @Override
                        public void onCompleted(Object o) {
                            loadingDialog.dismiss();
                            ToastUtil.showCenterToast("保存成功！");
                           if ("0".equals( mActivity.getStep())){
                               mActivity.setStep("1");
                               mActivity.setCurrentPage("1");
                           }
                        }

                        @Override
                        public void onError() {
                            loadingDialog.dismiss();
                            ToastUtil.showCenterToast("保存失败！");

                        }
                    });
//                    if (mIsLotDataSheet) {//保存 只能编辑实际工时
//                        //组件件号和序列号可以修改，修理零件号可以选择
//                        FragmentActivity context = getActivity();
//                        assert context != null;
////                        LoadingDialog loadingDialog = new LoadingDialog(context);
////                        loadingDialog.show();
////                        StaticPresenter.saveRoutingSheet()
//                    } else {//下一步
//                        //非成批零件  零件号 可以输入  显示搜索列表进行选择   实际工时
//                    }
                    break;
            }
        }
    };

}
